"""
Skeleton initialization code
"""
import optparse
from .print_ext import print_err
from sys import exit
import os.path
import shutil
import codecs
import uuid
import time

class OptionParser(optparse.OptionParser):
    def __init__(self):
        optparse.OptionParser.__init__(self, usage="%prog init [OPTIONS] <DIRECTORY>")
        self.add_option("-f", "--force", dest="force_overwrite", 
                        action="store_true", default=False,
                        help="Overwrite existing files in the specified directory")
        
templates_dir = None

def action(cmd_args):
    global templates_dir
    
    parser = OptionParser()
    (options, args) = parser.parse_args(args=cmd_args)
    
    if len(args) != 1:
        print_err("Path to the target directory is required")
        exit(1)
        
    target_dir = args[0]
    
    if templates_dir is None:
        # detect templates dir
        filedir = os.path.dirname(__file__)
        _templates_dir = os.path.normpath(os.path.join(filedir, "..", "templates"))
        
        if os.path.isdir(_templates_dir):
            # applicatiion is not installed
            templates_dir = _templates_dir
        else:
            print_err("Unable to find directory with templates")
            exit(1)
            
    # copy {templates_dir}/sample.mfb2 to {target_dir}/project.mfb2
    sample_filename = os.path.join(templates_dir, "sample.mfb2")
    target_filename = os.path.join(target_dir, "project.mfb2")
    
    if options.force_overwrite or not os.path.exists(target_filename):
        # copy file
        in_f = codecs.open(sample_filename, "r", encoding="utf-8")
        text = in_f.read()
        # replace some values
        text = text % {
           'uuid': str(uuid.uuid4()),
           'doc_date': time.strftime("%Y-%m-%d")
           }
        in_f.close()
        out_f = codecs.open(target_filename, "w", encoding="utf-8")
        out_f.write(text)
        out_f.close()


    content_filename = os.path.join(target_dir, "Makefile")
    if options.force_overwrite or not os.path.exists(content_filename):
        out_f = codecs.open(content_filename, "w", encoding="utf-8")
        text = """# Generated by metafb2
default:
\tmetafb2 compile project.mfb2

zip: default
\trm -f result.fb2.zip
\tzip result.fb2.zip result.fb2
"""
        out_f.write(text)
        out_f.close()
        
    # create content files if required
    content_files = ("content.txt", "annotation.txt", "notes.txt")
    
    for c in content_files:
        content_filename = os.path.join(target_dir, c)
        if not os.path.exists(content_filename):
            open(content_filename, "w").close()
            
